package com.acmen.easyapi.util;

import com.acmen.easyapi.annotation.ResParam;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.lang.reflect.Field;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @author acmen
 * @date 2022-04-07
 * 响应工具类
 */
public class ResponseUtil {
    private static final int ADJ_LEN = 2 << 11;
    public static Object refactorResponse(Object response, String client) {
        Field field = ClassUtil.getField(response.getClass(),"data");
        if(field==null){
            return response;
        }
        Object data = ClassUtil.getFieldValue(response,field);
        if(data==null){
            return response;
        }
        data = refactor(data,client);
        ClassUtil.setFieldValue(response,field,data);

        return response;
    }
    /**
     * 创建异常回应
     *
     * @return
     */
    public static Object refactor(Object data, String client) {
        if (data instanceof Collection) {
            Collection collection = (Collection) data;
            Iterator iterator = collection.iterator();
            JSONArray array = new JSONArray();
            while (iterator.hasNext()) {
                array.add(refactor(iterator.next(), client));
            }
            return array;
        } else if (ClassUtil.isBasicType(data.getClass())) {
            return data;
        } else if (data instanceof Date || data instanceof LocalDateTime
                || data instanceof LocalDate) {
            return data;
        } else {
            List<Field> fields = getFields(data.getClass());
            JSONObject jsonObject = new JSONObject();
            fields:
            for (Field field : fields) {
                Object value = ClassUtil.getFieldValue(data,field);
                value = refactor(value, client);
                ResParam resParam = ClassUtil.getAnnotation(field, ResParam.class);
                if (resParam == null || StringUtil.isEmpty(resParam.client())) {
                    jsonObject.put(field.getName(), value);
                } else if (resParam.client().equals(client)) {
                    jsonObject.put(field.getName(), value);
                }
            }
            return jsonObject;
        }
    }


    public static List<Field> getFields(Class class1) {
        List<Field> fieldList = new ArrayList<Field>();
        Field[] fields = class1.getDeclaredFields();
        for (Field field : fields) {
            if (!fieldList.contains(field)) {
                fieldList.add(field);
            }
        }
        Class<?> superclass = class1.getSuperclass();
        while (superclass != null && !superclass.equals(Object.class)) {
            fieldList.addAll(getFields(superclass));
            superclass = superclass.getSuperclass();
        }
        return fieldList;
    }
}
